<?php


namespace app\api\controller\v1;


use app\api\Validate\QiNiu\QiNiuDeleteFileValidate;
use app\BaseController;
use app\common\Token;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use think\App;
use think\facade\Env;

/**
 * 七牛云
 * Class QiNiu
 * @package app\api\controller\v1
 */
class QiNiu extends BaseController
{

    private Auth $auth; // 七牛云权限
    public function __construct(App $app)
    {
        parent::__construct($app);
        $accessKey = Env::get('qiniu.access_key');
        $secretKey = Env::get('qiniu.secret_key');
        $this->auth = new Auth($accessKey, $secretKey);
    }

    /**
     * 获取七牛云上传Token
     * @return \think\response\Json
     */
    public function getQiNiuToken()
    {
        Token::checkToken($this->request);
        try {
            $bucketName = Env::get('qiniu.bucket_name');
            $returnBody = json_encode([
                "code"=> 200,
                "msg" => "上传成功",
                "data" => [
                    "key" => "$(key)",
                    "hash" => "$(etag)",
                    "fsize" => "$(fsize)",
                ],
            ]);
            $policy = array(
                'returnBody' => $returnBody,
            );
            $uploadToken = $this->auth->uploadToken($bucketName, null, 7200, $policy);
            return successJson([
                "uploadToken" => $uploadToken,
            ], "获取Token成功");
        } catch (\Exception $e) {
            return errorJson(70001, "{$e->getMessage()}");
        }
    }

    /**
     * 获取七牛云文件列表
     * @return \think\response\Json
     */
    public function getQiuNiuList() {
        $bucketManager = new BucketManager($this->auth);
        $bucketName = Env::get('qiniu.bucket_name');
        list($ret, $err) =  $bucketManager->listFiles($bucketName, null, null, 100);
        if($err==null){
            return successJson($ret);
        }
        return errorJson(70002);
    }

    public function deleteQiNiuFile() {
        $keys = (new QiNiuDeleteFileValidate) -> validateParam();
        $bucketManager = new BucketManager($this->auth);
        $bucketName = Env::get('qiniu.bucket_name');
        list($ret, $err) =  $bucketManager::buildBatchDelete($bucketName, $keys);
    }
}